from selenium import webdriver
import os
import json
import time

TEST = False


def main():
	chromeoption = webdriver.ChromeOptions()
	if not TEST:
		chromeoption.add_argument('-headless')
		chromeoption.add_argument('--disable-gpu')
	
	chrome = webdriver.Chrome(chrome_options=chromeoption)
	try:
		chrome.get('https://live.bilibili.com/21377115')

		if os.path.exists('cookie.json'):
			with open('cookie.json','r',encoding='utf-8') as f:
				cookies = json.load(f)
			for cookie in cookies:
				if 'expiry' in cookie.keys():
					del cookie['expiry']
				chrome.add_cookie(cookie)
			chrome.refresh()
			if "登陆" not in chrome.find_element_by_tag_name('html').text:
				if TEST:
					chrome.execute_async_script('alert("已加载")')
				else:
					print('已加载')

		r = input('是否保存新cookie？[y/n]：')
		if r == 'y':
			with open('cookie.json','w',encoding='utf-8') as f:
				json.dump(chrome.get_cookies(),f)

		i = 0

		while True:
			i += 1
			chrome.find_element_by_css_selector('textarea[class="chat-input border-box"]').send_keys('#打卡\n')
			print('第{}次打卡'.format(i),time.ctime())
			try:
				time.sleep(31*60)
			except KeyboardInterrupt:
				break

		chrome.quit()

	except Exception as e:
		chrome.quit()
		del chrome
		raise e

if __name__ == '__main__':
		main()

	
